using System;
using System.Collections.Generic;
using System.Reflection;
using Nebulosa.Data.Providers;

namespace Nebulosa.Data.Orm {
	public class Model {
		public void Insert() {
			this.Insert(DbProvider.Instance);
		}
		
		public void Insert(DbProvider provider) {
			//provider.Insert<this.GetType()>(this);
			Type type = this.GetType();
			
			MethodInfo genericMethod = provider.GetType().GetMethod("Insert").MakeGenericMethod(new Type[] { type });
			genericMethod.Invoke(provider, new object[] {this}); // No target, no arguments
		}
		
		public void Update() {
		
		}
		
		public void Delete() {
		
		}
		
		public Model Get() {
			return this.Get(DbProvider.Instance);
		}
		
		public Model Get(DbProvider provider) {
			return provider.Get<Model>(this);
		}
		
		public void Hidrate() {
		
		}
		
		public List<PropertyInfo> GetPrimaryKeys() {
			List<PropertyInfo> primaryKeys = new List<PropertyInfo>();
			
			PropertyInfo[] properties = this.GetType().GetProperties();
			for(int i = 0; i < properties.Length; i++) {
				PrimaryKeyAttribute[] attrPK = (PrimaryKeyAttribute[])properties[i].GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
				if(attrPK.Length > 0) {
					primaryKeys.Add(properties[i]);
				}
			}
			
			return primaryKeys;
		}
		
		public List<PropertyInfo> GetIndexes() {
			return this.GetIndexes(false);
		}
		
		public List<PropertyInfo> GetIndexes(bool unique) {
			List<PropertyInfo> indexes = new List<PropertyInfo>();
			
			PropertyInfo[] properties = this.GetType().GetProperties();
			for(int i = 0; i < properties.Length; i++) {
				IndexAttribute[] attrIndex = (IndexAttribute[])properties[i].GetCustomAttributes(typeof(IndexAttribute), true);
				if(attrIndex.Length > 0) {
					if(!unique || (unique && attrIndex[0].Unique)) {
						indexes.Add(properties[i]);
					}
				}
			}
			
			return indexes;
		}
		
		public void GetFields() {
		
		}
	}
}